<template>
    <section>
        <div style="margin-bottom:5px;">
            <el-input placeholder="请输入内容" size="small" v-model="searchKey" style="width: 250px;">
                <el-button slot="append" size="small"  icon="el-icon-search" @click="getDataList"></el-button>
            </el-input>
            <el-button type="primary" size="small" @click="openAddDialog()">新 建</el-button>
        </div>
        <el-table ref="multipleTable" :data="dataList" border tooltip-effect="dark" style="width: 100%"
                  @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" label="序号">
            </el-table-column>
            <el-table-column prop="code" label="编码">
            </el-table-column>
            <el-table-column prop="name" label="名称">
            </el-table-column>
            <el-table-column prop="admin" label="是否超管">
                <template slot-scope="scope">
                    <el-tag v-if="scope.row.admin" type="success">是</el-tag>
                    <el-tag v-else type="danger">否</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="description" label="描述" width="350">
            </el-table-column>

            <el-table-column  label="操作" width="420">
                <template slot-scope="scope">
                    <el-button-group>
                        <el-button size="mini" v-if="!scope.row.admin" type="primary" @click="openAssignDialog(scope.row.id)">分配权限</el-button>

                        <el-button size="mini" type="primary" @click="openAssignOrgDialog(scope.row.id)">分配人员
                        </el-button>

                        <el-button size="mini" type="primary" @click="openDialog(scope.row)">编辑</el-button>
                        <el-button size="mini" type="danger" @click="removeItem(scope.row)">删除</el-button>
                    </el-button-group>
                </template>
            </el-table-column>
        </el-table>
        <div style="text-align: right;background: rgb(239, 242, 247);border: 1px solid #E5E9F2;">
            <el-pagination style="line-height: 30px; height: 30px;" @size-change="handleSizeChange"
                           @current-change="handleCurrentChange" :current-page="currentPage"
                           :page-sizes="[10, 20, 30, 50]" :page-size="pageSize"
                           layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
        </div>
        <el-dialog :title="dialogAddOrEdit" :visible="dialogFormVisibleAdd"  :modal="dialogFormVisibleAdd"   :before-close="openAddDialogClose">

            <el-form label-width="100px" :rules="formAddRules" :model="formAdd" ref="formAdd">


                <el-row>
                    <el-col :span=12>
                        <el-form-item label="编码" prop="code">
                            <el-input v-model="formAdd.code" style="width: 100%"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span=12>
                        <el-form-item label="名称" prop="name">
                            <el-input v-model="formAdd.name"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span=12>
                        <el-form-item label="描述" prop="description">
                            <el-input 　 v-model="formAdd.description"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span=12>
                        　
                    </el-col>
                </el-row>

                <el-form-item>
                    <el-button type="primary" @click="submitFormAdd('formAdd')">保存</el-button>
                    <el-button @click="openAddDialogClose">取消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>

        <el-dialog :title="formAssign.authTitle" :visible="formAssign.dialogVisible" oncancel="clearData()"
                   onclose="clearData()" :before-close="openAssignOrgDialogClose">
            <el-form label-width="100px" :model="formAssign" ref="formAssign">


                <div style="height: 370px;overflow: auto;">
                    <el-tree ref="tree" node-key="id"   :default-expanded-keys="formAssign.checkedKeys"
                             :default-checked-keys="formAssign.checkedKeys" :data="formAssign.authData"
                             :props="treeProps" show-checkbox check-strictly ></el-tree>
                </div>

                <el-form-item>
                    <el-button type="primary" @click="submitFormAssignAuth()">保存</el-button>
                    <el-button @click="formAssign.dialogVisible = false">取消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>

        <div v-if="userDialog.userDialogVisible">
        <user-dialog :DialogVisible="userDialog.userDialogVisible"
                     :params="{user: userDialog.selectUser,orgType:userDialog.orgTypeValue}"
                     @on-dialog-change="onDialogChange"
          ></user-dialog>
        </div>
    </section>
</template>
<style>

</style>
<script>
    import {AjaxByAll} from '@/api/api';
    import userDialog from '@/views/common/userDialog.vue'

    export default {
        data() {

            return {
                dataList: [],
                multipleSelection: [],
                dialogFormVisibleAdd: false,
                labelPosition: 'left',
                formAdd: {
                    id: null,
                    name: null,
                    code: null,

                    description: null,
                    projectCode: null,


                },
                projectCode:null,
                defaultData: null,
                pageSize: 10,
                currentPage: 1,
                total: 0,
                dialogAddOrEdit: '',
                searchKey: null,
                formAddRules: {

                    name: [
                        {required: true, message: '请填写名称', trigger: 'blur'}
                    ],
                    code: [
                        {required: true, message: '请输入 编码', trigger: 'blur'}
                    ]
                },
                dialogFormVisibleAssignAuth: false,
                formAssign: {
                    dialogVisible:false,
                    authData: null,
                    checkedKeys: [],
                    roleId: null,
                    authTitle: "分配权限"
                },

                treeProps: {
                    label: 'name',
                    children: 'children'
                }
                ,
                userDialog: {
                    roleId: null,
                    userDialogVisible: false,
                    selectUser: [],
                    orgTypeValue: 3
                }

            }
        },

        methods: {
            openDialog(model) {

                if (model) {
                    let id = model.id;
                    this.dialogAddOrEdit = '编辑角色';
                    let urls = 'gateway/auth/role/' + id;
                    let method = 'get';
                    let form = {};
                    AjaxByAll(method, urls, form).then(data => {
                        if (data.code === 200) {
                            this.formAdd = data.data;
                        } else {
                            this.$Message.error(data.msg);
                        }
                    });
                }
                this.dialogFormVisibleAdd = true;
            },
            openAddDialog() {
                this.dialogAddOrEdit = '新建角色';
                // 送出後
                this.$data.formAdd = Object.assign(this.$data.formAdd, this.defaultData);
                this.formAdd.projectCode=this.projectCode;
                this.dialogFormVisibleAdd = true;
            },
            openAddDialogClose () {

                this.dialogFormVisibleAdd = false;
            },
            getDataList() {
                let self = this;
                let form = {
                    currentPage: self.currentPage,
                    pageSize: self.pageSize,
                    keyword: self.searchKey,
                    projectCode:self.projectCode,
                };
                let urls = 'gateway/auth/role/query';
                AjaxByAll('post', urls, form).then(data => {
                    if (data.code === 200) {

                        self.total = data.data.total*1;
                        self.dataList = data.data.records;
                    }

                    this.loading = false;
                });
            },
            submitFormAdd(formName) {

                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        let form = this.formAdd;
                        let urls = 'gateway/auth/role/';
                        let method = this.formAdd.id
                        == null ? 'post' : 'put';
                        AjaxByAll(method, urls, form).then(data => {
                            if (data.code === 200) {
                                this.formAdd.id = data.data.id;
                                this.$message({
                                    message: '操作成功',
                                    type: 'success'
                                });

                                this.getDataList();
                            } else {
                                this.$message({
                                    message: data.msg,
                                    type: 'error'
                                });
                            }
                            this.dialogFormVisibleAdd = !this.dialogFormVisibleAdd;
                        });


                    } else {
                        this.$message({
                            message: '校验失败',
                            type: 'error'
                        });
                    }
                });
            },
            removeItem(model) {
                this.$confirm('确认移除吗?', '提示', {
                    type: 'warning'
                }).then(() => {
                    AjaxByAll('delete', 'gateway/auth/role/' + model.id, null).then(data => {
                        if (data.code === 200) {
                            this.$message({
                                message: '操作成功',
                                type: 'success'
                            });
                            this.getDataList();
                        } else {
                            this.$message({
                                message: '操作失败：' + data.msg,
                                type: 'error'
                            });
                        }

                    });
                }).catch(() => {

                });
            },
            toggleSelection(rows) {
                if (rows) {
                    rows.forEach(row => {
                        this.$refs.multipleTable.toggleRowSelection(row);
                    });
                } else {
                    this.$refs.multipleTable.clearSelection();
                }
            },
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            handleSizeChange(val) {
                console.log(`每页 ${val} 条`);
                this.pageSize = val;
                this.getDataList();
            },
            handleCurrentChange(val) {
                console.log(`当前页: ${val}`);
                this.currentPage = val;
                this.getDataList();
            },


            openAssignDialog(roleId) {

                this.formAssign.roleId = roleId;

                let urls = 'gateway/auth/resource/resourceTree';
                let method = 'post';
                let form = {};
                AjaxByAll(method, urls, form).then(data => {
                    if (data.code === 200) {
                        this.formAssign.authData = data.data;
                        //加载选中的资源
                        AjaxByAll("get", 'gateway/auth/role/resource/' + roleId, form).then(data => {
                            if (data.code === 200) {

                                this.formAssign.checkedKeys = data.data;

                                //加载选中的资源
                                this.formAssign.dialogVisible = true;
                                this.$nextTick(() => {
                                    this.$refs.tree.setCheckedKeys(this.formAssign.checkedKeys,true);

                                });

                            } else {
                                this.$message({
                                    message: '操作失败：' + data.msg,
                                    type: 'error'
                                });
                            }
                        });
                    } else {
                        this.$message({
                            message: '操作失败：' + data.msg,
                            type: 'error'
                        });
                    }
                });
            },
            submitFormAssignAuth() {
                let urls = 'gateway/auth/role/resource/' + this.formAssign.roleId;
                let form = {"id": this.$refs.tree.getCheckedKeys()};
                AjaxByAll("put", urls, form).then(data => {
                    if (data.code === 200) {
                        this.$message({
                            message: '操作成功',
                            type: 'success'
                        });
                        this.formAssign.dialogVisible = false;
                    } else {
                        this.$message({
                            message: '操作失败：' + data.msg,
                            type: 'error'
                        });
                    }
                });

            }, clearData() {
                this.formAssign.roleId = null;
                this.formAssign.checkedKeys=null;

            },
            openAssignOrgDialogClose(){
                this.dialogFormVisibleAssignAuth = false;
            },
            openAssignOrgDialog(roleId) {
                this.userDialog.roleId = roleId;
                //加载选中的资源
                AjaxByAll("get", 'gateway/auth/role/org/' + roleId, {}).then(data => {
                    if (data.code === 200) {

                        this.userDialog.selectUser = data.data;

                        this.userDialog.userDialogVisible = true;
                    } else {
                        this.$Message.error(data.msg);
                    }
                });
            },
            onDialogChange(val) {
                if(!val.onSubmitData){
                    this.userDialog.userDialogVisible = false;
                    return ;
                }
                let urls = 'gateway/auth/role/org/' + this.userDialog.roleId;
;
                let form = val.users;

                AjaxByAll("put", urls, form).then(data => {
                    if (data.code === 200) {
                        this.$message({
                            message: '操作成功',
                            type: 'success'
                        });
                        this.userDialog.userDialogVisible = false;
                    } else {
                        this.$message({
                            message: '操作失败：' + data.msg,
                            type: 'error'
                        });
                    }
                });
                this.userDialog.selectUser = [];
            }

        },
        created() {
            this.defaultData = JSON.parse(JSON.stringify(this.formAdd));
            this.formAssign.checkedKeys = [];
            this.projectCode=this.$route.params.projectCode;
        },
        mounted: function () {
            this.getDataList();
        }, components: {
            userDialog
        }
    }
</script>
